package com.ansion.baseui.base.recycler;

import android.animation.ValueAnimator;
import android.graphics.Rect;
import android.view.View;
import android.view.animation.DecelerateInterpolator;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public abstract class SearchBarSpringAnimation {

    private ValueAnimator offsetAnimator;

    public void play(RecyclerView recyclerView) {
        if (recyclerView.getVisibility() != View.VISIBLE || !recyclerView.isShown() || !recyclerView.getGlobalVisibleRect(new Rect())) {
            return;
        }

        if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
            try {
                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int firstVisibleItem = manager.findFirstVisibleItemPosition();
                View view = manager.findViewByPosition(firstVisibleItem);
                if (view == null || view.getVisibility() != View.VISIBLE || !view.isShown() || !view.getGlobalVisibleRect(new Rect())) {
                    return;
                }
                if (!isSearchType(recyclerView, firstVisibleItem)) {
                    return;
                }
                Rect rect = new Rect();
                boolean cover = view.getGlobalVisibleRect(rect);
                if (cover && rect.height() > view.getMeasuredHeight() / 2f) {
                    final float distanceRatio = (float) Math.abs(view.getTop()) / view.getMeasuredHeight();
                    int duration = (int) ((distanceRatio + 1) * 150);
                    recyclerView.smoothScrollBy(0, view.getTop(), new DecelerateInterpolator(), Math.min(duration, 600));
                } else {
                    final float distanceRatio = (float) rect.height() / view.getMeasuredHeight();
                    int duration = (int) ((distanceRatio + 1) * 150);
                    smoothScroll(manager, rect.height(), duration);
                }
            } catch (Exception e) {

            }
        }
    }

    private void smoothScroll(LinearLayoutManager manager, int currentOffset, int duration) {
        if (offsetAnimator == null) {
            offsetAnimator = new ValueAnimator();
            offsetAnimator.setInterpolator(new DecelerateInterpolator());
            offsetAnimator.addUpdateListener(animator -> {
                manager.scrollToPositionWithOffset(1, (int) animator.getAnimatedValue());
            });
        } else {
            offsetAnimator.cancel();
        }

        offsetAnimator.setDuration(Math.min(duration, 600));
        offsetAnimator.setIntValues(currentOffset, 0);
        offsetAnimator.start();
    }


    public abstract int getSearchType();

    public boolean isSearchType(RecyclerView recyclerView, int firstVisibleItem) {
        return recyclerView.getAdapter() != null && recyclerView.getAdapter().getItemViewType(firstVisibleItem) == getSearchType();
    }
}
